package cn.thoughtworks.school.programCenter.repositories;

import cn.thoughtworks.school.programCenter.entities.Task;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

public interface TaskRepository extends JpaRepository<Task, Long> {
    List<Task> findTaskByTopicIdOrderByOrderNumberAsc(Long topicId);

    List<Task> findTaskByProgramIdAndVisible(Long programId, Boolean visible);

    List<Task> findByProgramId(Long programId);

    @Modifying
    @Transactional
    @Query("update Task set visible=?2 where topicId=?1")
    void updateVisibilityByTopicId(Long id, Boolean visible);
    
    List<Task> findByVisibleIsTrueAndProgramIdAndTopicIdAndOrderNumberGreaterThanOrderByOrderNumberAsc(Long programId, Long topicId, Long orderNumber);

    List<Task> findByProgramIdAndTopicIdAndVisibleIsTrueOrderByOrderNumberAsc(Long programId, Long topicId);

    List<Task> findByVisibleIsTrueAndProgramIdAndTopicIdAndOrderNumberLessThanOrderByOrderNumberDesc(Long programId, Long topicId, Long orderNumber);

    @Modifying
    @Transactional
    @Query("update Task set programId=?2, topicId=?3 where id in ?1")
    void moveTasksToTopic(List<Long> sourceTaskIds, Long programId, Long topicId);

    List<Task> findByTopicIdAndVisibleOrderByOrderNumberAsc(Long programId, Boolean visible);

    List<Task> findByVisibleIsTrueAndTopicIdIn(List<Long> topicIds);

    @Query("select programId from Task where id = ?1")
    Long findProgramIdByTaskId(Long taskId);

    List<Task> findByProgramIdIn(List<Long> ids);

    List<Task> getTasksByIdIn(List<Long> taskIdList);

    List<Task> findByProgramIdInAndVisibleIsTrueOrderByOrderNumberAsc(List<Long> programIds);


    Optional<Task> findByIdAndVisibleIsTrue(Long taskId);

    List<Task> findByIdIn(List<Long> ids);
}
